<template>
  <div>
    <component
      :is="schema.type"
      :options="schema.options"
      :data="schema.data"
      v-bind="$data"
      @input="onInput"
    >
      <item
        v-for="(item, key) in schema.children"
        :schema="item"
        v-bind="{options: item.options, resolver, binding}"
        v-on="$listeners"
        :path="[...path, key]"
        :key="key"
      ></item>
      <template v-for="(item, key) in schema.slots" v-slot:[key]="iValue">
        <component :is="item.type" v-bind="iValue" :key="key">
          <!-- 作用域模板嵌套 -->
          <item
            v-for="(i, k) in item.children"
            :schema="i"
            v-bind="{options: i.options, resolver, binding}"
            v-on="$listeners"
            :path="[...path, key, k]"
            :key="k"
          ></item>
        </component>
      </template>
    </component>
  </div>
</template>
<script>
export default {
  name: "item",
  data() {
    const dataDeclaration = this.schema.data
      ? Object.keys(this.schema.data)
      : [];
    //let a = this.$refs.com
    let r = { dataDeclaration };
    for (let k of dataDeclaration) {
      r[k] = null;
    }
    return r;
  },
  async created() {
    for (let k of this.dataDeclaration) {
      let o = this.schema.data[k],
        r = await this.resolver[o.type](o, this.binding, this.$parent);
      this.$data[k] = r;
    }
  },
  methods: {
    onInput(ev) {
      this.$emit("change", { path: this.path, type: "input", value: ev });
    },
    change(ev) {
      this.$emit("change", ev);
    }
  },
  props: {
    path: {
      type: Array,
      default() {
        return [];
      }
    },
    resolver: {
      type: Object
    },
    schema: {
      type: Object,
      default() {
        return {};
      }
    },
    binding: {
      type: Object
    }
  }
};
</script>